<template>
    <el-row class="padd20 bgf main-cont">
        <el-col class="posa padd20">
            <el-col class="mb20">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/ldsj_jyzz' }">实践课程</el-breadcrumb-item>
                    <el-breadcrumb-item>{{tip}}</el-breadcrumb-item>
                </el-breadcrumb>
            </el-col>
            <el-col class="btn">
                <el-col class="padd20">
                    <el-form ref="lineForm" :rules="rules" :model="lineForm" label-width="110px" class="reset-form"
                        style="display: flex;">
                        <el-col style="width: 50%;">
                            <el-col class="tl">
                                <div class="title">
                                    基本信息
                                </div>
                            </el-col>
                            <el-col>
                                <el-form-item label="标题" prop="title">
                                    <el-input v-model="lineForm.title" class="text" :disabled="isDisabled"></el-input>
                                </el-form-item>
                                <el-form-item label="劳动分类" prop="sjtype1">
                                    <el-col class="box">
                                        <el-select v-model="lineForm.sjtype1" placeholder="请选择" class="text"
                                            @change="getDictByVal" :disabled="isDisabled">
                                            <el-option :label="v.name" :value="v.val" v-for="(v,i) in options"
                                                :key="i"></el-option>
                                        </el-select>
                                        <el-select v-model="lineForm.sjtype2" placeholder="请选择" class="text" :disabled="isDisabled">
                                            <el-option :label="v.name" :value="v.val" v-for="(v,i) in optionsList"
                                                :key="i"></el-option>
                                        </el-select>
                                    </el-col>

                                </el-form-item>
                                <el-form-item label="实践封面" prop="img" ref="sjImage">
                                    <el-col class="box box-align-end box-pack-start">
                                        <el-col>
                                            <el-upload class="avatar-uploader" :action="uploadfileurlSj" :disabled="isDisabled"
                                                :show-file-list="false" :limit="1" accept=".jgp, .png, .jpeg"
                                                :on-progress="progressSj" :on-success="successSj"
                                                :before-upload="beforeUploadSj">
                                                <!-- <img v-if="lineForm.img" :src="lineForm.img" class="avatar"> -->
                                                <el-image v-if="lineForm.img" :src="lineForm.img" class="avatar"
                                                    fit="cover"></el-image>
                                                <div v-else class="upload-icon">
                                                    <i class="el-icon-upload"></i>
                                                    <div>上传</div>
                                                </div>
                                            </el-upload>
                                            <el-progress v-if="showProgressSj" :percentage="progIntSj"></el-progress>
                                        </el-col>
                                      <!--  <el-col>
                                            <el-button type='text' @click="dialogVisible = true">选择系统封面</el-button>
                                        </el-col> -->
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="劳动目标" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.ldmb" :disabled="isDisabled"></el-input>
                                </el-form-item>
                                <el-form-item label="场所与工具" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.csygj" :disabled="isDisabled"></el-input>
                                </el-form-item>
                                <el-form-item label="劳动安全与规则" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.aqygz" :disabled="isDisabled"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-col>
                       <el-dialog title="选择系统封面" :visible.sync="dialogVisible" width="600px"
                            @close="dialogVisible = false" :center="false">
                            <el-col class="fm">
                                <el-image :src="item.url" v-for="(item,index) in imageUrls" :key="index"
                                    class="mr10 mb5 cp img" :class="{active:current == index}"
                                    @click="changeFm(item,index)"></el-image>
                            </el-col>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="confirm()">确 定</el-button>
                            </span>
                        </el-dialog>
                        <el-col style="width: 60%; margin:0 0 0 100px;">
                            <el-col class="tl">
                                <div class="title">
                                    实践操作
                                </div>
                            </el-col>
                            <el-col>
                                <el-form-item label="组织准备" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.zzzb" :disabled="isDisabled"></el-input>
                                </el-form-item>
                                <el-form-item label="具体流程" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.jtly" :disabled="isDisabled"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col class="tl">
                                <div class="title">
                                    评价标准（{{totalScore}}分）
                                </div>
                            </el-col>
                            <el-col>
                                <el-form-item v-for="(domain, index) in lineForm.pfbzs" :label="''+(index+1)"
                                    :key="index" :prop="'pfbzs.' + index + '.cont'" :rules="{
                                      required: true, message: '请填写评分标准', trigger: 'blur'
                                    }" class="item">
                                    <el-input v-model="domain.cont" class="text" :disabled="isDisabled"></el-input>
                                    <el-input-number v-model="domain.score" controls-position="right" :min="1" :disabled="isDisabled"
                                        :max="100" class="mr20 ml20" @change="resetScore()"></el-input-number>
                                    分
                                    <el-button @click.prevent="removeDomain(domain)" class="ml10 reset-cancel-btn"  :disabled="isDisabled">删除
                                    </el-button>
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="addDomain" type="infor" v-if="!isDisabled">+添加</el-button>
                                </el-form-item>
                                <el-form-item style="position: absolute;right: 50px;margin-top: 80px;">
                                    <el-button class="reset-cancel-btn" @click="handleClose('lineForm')">返 回</el-button>
                                    <el-button class="reset-comfirm-btn" @click="onSubmit('lineForm')" v-if="!isDisabled">保 存</el-button>
                                </el-form-item>
                            </el-col>
                        </el-col>
                    </el-form>
                </el-col>
            </el-col>
        </el-col>
    </el-row>
</template>

<script>
    import minxins from "@/utils/dictMinxins.js";
    export default {
        mixins: [minxins],
        data() {
            return {
                tip: "创建劳动实践",
                loginInfo: this.$store.state.loginInfo,
                jyzid: this.$store.state.jyzid,
                totalScore: 0,
                imageUrls: [],
                lineForm: {
                    id: '',
                    title: '',
                    sjtype1: '',
                    sjtype2: '',
                    img: '',
                    fileName: '',
                    fileid: '',
                    ldmb: '',
                    csygj: '',
                    aqygz: '',
                    zzzb: '',
                    jtly: '',
                    pfbzs: [{
                        cont: '',
                        score: 0
                    }],
                    img: '',
                    sjVideoImage: '',
                    url: ''
                },
                rules: {
                    name: [{
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur'
                    }],
                    sjtype1: [{
                        required: true,
                        message: '请选择劳动分类',
                        trigger: 'change'
                    }],
                    fileid: [{
                        required: true,
                        message: '请上传视频',
                        trigger: 'change'
                    }],
                    img: [{
                        required: true,
                        message: '请上传封面',
                        trigger: 'change'
                    }],
                },
                showProgress: false,
                showProgressSj: false,
                progInt: 0,
                progIntSj: 0,
                uploadfileurl: this.$url.baseURL + '/upload/uploadfile',
                uploadfileurlSj: this.$url.baseURL + '/upload/uploadfile',
                dialogVisible: false,
                current: 0,
                diaImg: '',
                maxRole: this.$store.state.maxRole,
				
            }
        },
        computed: {
            isEdit() {
                return this.$route.meta.isEdit //根据meta判断
            },
			isDisabled(){
				console.log(localStorage.getItem('isDisabled')== `true`);
				return localStorage.getItem('isDisabled')== `true`
			}
        },
        created() {
            this.getDict()
            if (this.isEdit) {
                this.tip = "编辑劳动实践"
                this.ldsjInfo();
				if(localStorage.getItem('isDisabled') == `true`){
					this.tip = "详情"
				}
            } else {
                this.tip = "创建劳动实践"
            }
        },
		watch:{
			
		},
        mounted() {
            this.resetScore()
        },
        methods: {
            getDict(){
                let params = {
                    code:'sjtype'
                }
                this.$api.wyv3.getDictList(params).then(res=>{
                    if(res.code == 200){
                        this.options = res.data
                        this.getDictByVal(res.data[0].val)
                        if(!this.isEdit){
							if(localStorage.getItem('isDisabled') == `false`)
                            this.lineForm.sjtype1 = res.data[0].val
                        }
                    }
                })
            },
            //获取二级数据
            getDictByVal(val){
                let params = {
                    val:val
                }
                this.$api.wyv3.getDictByVal(params).then(res=>{
                    if(res.code == 200){
                        this.optionsList = res.data
						if(!this.isEdit){
							if(localStorage.getItem('isDisabled') == `false`)
						    this.lineForm.sjtype2 = res.data[0].val
						}
                    }
                })
            },
            ldsjInfo(){
                this.$api.jyz.ldsjInfo({
                    id: localStorage.getItem('ldsjId')
                }).then(res => {
                    console.log(res);
                    if (res.code == '0') {
                        this.$nextTick(()=>{
                            this.lineForm = Object.assign(this.lineForm,res.info)
                        })
                    } else {
                        this.$message.error('请求失败！');
                    }
                })
            },
            showVideo(url) {
                window.open(url);
            },
            changeFm(item, index) {
                this.current = index;
                this.diaImg = item.url
                this.$refs['sjImage'].clearValidate()
            },
            confirm() {
                this.dialogVisible = false
                this.lineForm.img = this.diaImg
            },
            //获取编辑数据
            getEditData() {
                this.lineForm.id = this.sj.id,
                    this.lineForm.name = this.sj.title,
                    this.lineForm.sjtype1 = this.sj.typeId,
                    this.lineForm.img = this.sj.img,
                    this.lineForm.ldmb = this.sj.ldmb,
                    this.lineForm.csygj = this.sj.csygj,
                    this.lineForm.aqygz = this.sj.aqygz,
                    this.lineForm.zzzb = this.sj.zzzb,
                    this.lineForm.jtly = this.sj.jtly,
                    this.lineForm.pfbzs = this.sj.pfbzs
            },
            removeDomain(item) {
                var index = this.lineForm.pfbzs.indexOf(item)
                var len = this.lineForm.pfbzs.length
                if (len !== 1) {
                    this.lineForm.pfbzs.splice(index, 1)
                }
                this.resetScore()
            },
            resetScore() {
                if (this.lineForm.pfbzs != undefined) {
                    this.totalScore = 0
                    let score = this.lineForm.pfbzs.map(res => {
                        return res.score
                    })
                    score.forEach(res => {
                        this.totalScore = this.totalScore + res
                    })
                }
            },
            addDomain() {
                this.lineForm.pfbzs.push({
                    cont: '',
                    score: 0,
                });
                this.resetScore()
            },
            handleClose(formName) {
                this.$refs[formName].resetFields();
                this.$router.go(-1)
            },
            progressSj(event) {
                this.showProgressSj = true;
                this.progInt = parseInt(event.loaded / event.total * 100, 10);
            },
            successSj(response, file, fileList) {
                this.showProgressSj = false;
                this.lineForm.img = response.body.data.url;
                this.$refs['sjImage'].clearValidate()
            },
            beforeUploadSj(file) {
                const fileName = file.name;
                const index = fileName.lastIndexOf(".");
                const ext = fileName.substr(index + 1);
                const arr = ["jpg", "png", "jpeg"];
                const isOk = arr.includes(ext);
                if (!isOk) {
                    this.$message.warning('封面格式暂不支持！');
                    return false;
                }
                let imgSize = file.size / (1024 * 1024);
                if (imgSize > 50) {
                    this.$message.warning(`当前文件${ parseInt(imgSize) }M,上传文件不能超过50M`)
                    return false
                }
            },
            //
            typeValue() {
                return this.options.map(res => {
                    let str;
                    if (this.lineForm.sjtype1 == res.val) {
                        str = res
                    }
                    return str
                }).filter(o => o != undefined)[0].startTime
            },
            onSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = Object.assign({}, this.lineForm)
                        params.createUser = this.loginInfo.user.id
                        params.type = this.typeValue()
                        params.jyzId =  this.maxRole != 'cmo'?this.jyzid:''
                        params.schoolId = this.maxRole != 'cmo'?this.loginInfo.user.schoolId:''
                        delete params.status
                        delete params.userName
                        delete params.updateUser
                        delete params.createTime
                        delete params.updateTime
                        delete params.fileName
                        delete params.fileid
                        delete params.sjVideoImage
                        delete params.url
                        delete params.sjtypename1
                        delete params.sjtypename2
                        console.log(JSON.stringify(params));
                        this.$api.jyz.addLdsj({
                            str: JSON.stringify(params)
                        }).then(res => {
                            if (res.code == '0') {
                                this.$message.success('操作成功！');
                                this.$router.go(-1)
                            } else {
                                this.$message.error('操作失败！');
                            }
                        })
                    } else {
                        return false;
                    }
                });

            },
            progress(event) {
                this.showProgress = true;
                this.progInt = parseInt(event.loaded / event.total * 100, 10);
            },
            success(response, file, fileList) {
                this.showProgress = false;
                this.lineForm.sjVideoImage = response.body.data.firstframe;
                this.lineForm.fileName = response.body.data.fileName;
                this.lineForm.fileid = response.body.data.fileid;
                this.lineForm.url = response.body.data.url;
                console.log(response)
            },
            beforeUpload(file) {
                const fileName = file.name;
                const index = fileName.lastIndexOf(".");
                const ext = fileName.substr(index + 1);
                const arr = ["mp4"];
                const isOk = arr.includes(ext);
                if (!isOk) {
                    this.$message.warning('视频格式暂不支持！');
                    return false;
                }
                var imgSize = file.size / (1024 * 1024);
                if (imgSize > 500) {
                    this.$message.warning(`当前文件${ parseInt(imgSize) }M,上传文件不能超过500M`)
                    return false
                }
            },
            handleSelect() {

            }
        }
    };
</script>

<style scoped lang="scss">
    .main-cont {
        position: relative;

        .posa {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            width: 100%;
            overflow-y: auto;
        }

    }

    .upload-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 110px;
        height: 110px;
        line-height: 110px;
        color: #6872ff;
        font-size: 30px;
        border-radius: 10px;
        border: .1px #e7ebf0 solid;

        div {
            height: 20px;
            line-height: 20px;
            font-size: 10px;
            color: #a7abb1;

        }

        &:hover {
            color: #626BF1;

            div {
                color: #626BF1;
            }
        }
    }


    .avatar {
        width: 110px;
        height: 110px;
    }

    .item>>>.el-form-item__content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .avatar {
        width: 110px;
        height: 110px;
    }

    .bgf {
        height: 100%;
        background-color: #fff;
        overflow-y: auto;
    }

    .fm .img {
        border: 1px solid #ccc;

        &.active,
        &:hover {
            border: 1px solid #00aaff;
        }
    }
</style>
